package com.mogist.hqc.module.personal.ui

import android.content.Intent
import android.os.Build
import android.view.View
import android.view.WindowManager
import butterknife.OnClick
import butterknife.Optional
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.event.WXEvent
import com.mogist.hqc.entitys.response.LoginVo
import com.mogist.hqc.module.personal.contract.LoginContract
import com.mogist.hqc.module.personal.presenter.LoginPresenter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.util.Constant
import com.mogist.hqc.util.Util
import com.mogist.hqc.view.PhoneCode
import com.tencent.mm.opensdk.modelmsg.SendAuth
import kotlinx.android.synthetic.main.activity_login.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import talex.zsw.basecore.util.*
import talex.zsw.basecore.view.dialog.sweetalertdialog.SweetAlertDialog
import talex.zsw.basecore.view.other.RxToast
import java.util.*

/**
 * 作用：登录
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class LoginActivity : BaseMVPActivity<LoginContract.Presenter>(), LoginContract.View
{
    var mobile = ""
    override fun initArgs(intent: Intent?)
    {
    }

    override fun initView()
    {
        setContentView(R.layout.activity_login)
        mPresenter = LoginPresenter(this)
        //当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            //透明状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        }
    }

    override fun initData()
    {
        mEtTel.setAfterChangedListener { s ->
            mTvSend.isEnabled = RegTool.isMobileSimple(s)
        }

        mPhoneCode.setOnInputListener(object : PhoneCode.OnInputListener
                                      {
                                          override fun onSucess(code: String)
                                          {
                                              LogTool.nd("code = $code")
                                              val body = BaseModel()
                                              body.mobile = mobile
                                              body.checkCode = code
                                              mPresenter.getData(HttpDto(Constant.LOGIN,
                                                                         body).setErrorTitle("登录失败"))
                                          }

                                          override fun onInput()
                                          {
                                              LogTool.nd("onInput")
                                          }
                                      })
    }

    override fun onBackPressed()
    {
        exit()
    }

    @Optional
    @OnClick(R.id.mTvSend, R.id.mTvCode, R.id.mTvMore, R.id.mIvBack)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mTvSend ->
                {
                    mobile =
                            mEtTel.text.toString()
                                    .trim()
                    val body = BaseModel()
                    body.mobile = mobile
                    mPresenter.getData(HttpDto(Constant.LOGIN_SEND, body).setErrorTitle("发送验证码失败"))
                }
                R.id.mTvCode ->
                {
                    val body = BaseModel()
                    body.mobile = mobile
                    mPresenter.getData(HttpDto(Constant.LOGIN_SEND, body).setErrorTitle("发送验证码失败"))
                }
                R.id.mTvMore ->
                {
                    if (!mApplication.wxApi.isWXAppInstalled())
                    {
                        RxToast.error("您还未安装微信客户端")
                        return
                    }
                    // send oauth requeiest
                    val req = SendAuth.Req()
                    req.scope = "snsapi_userinfo"
                    req.state = "hqc"
                    mApplication.wxApi.sendReq(req)

                }
                R.id.mIvBack ->
                {
                    exit()
                }
            }
        }
    }

    private fun exit()
    {
        showDialog(SweetAlertDialog.WARNING_TYPE, "是否放弃登录？", "", "确定", "取消", {
            finish()
        }, null)
    }

    override fun sendSuccess()
    {
        mLLTel.visibility = View.GONE
        mTvMore.visibility = View.GONE
        mLLCode.visibility = View.VISIBLE
        mTvCode.isClickable = false
        mTvCode.setTextColor(ColorTool.getColorById(R.color.text_black3))
        Tool.countDown(mTvCode,
                       60 * 1000,
                       1000,
                       DataTool.getString(R.string.login_count_down),
                       DataTool.getString(R.string.login_resend)) {
            mTvCode.isClickable = true
            mTvCode.setTextColor(ColorTool.getColorById(R.color.text_orange))
        }
        mPhoneCode.showSoftInput()
        val phone = getResources().getString(R.string.login_code_send)
        mTvPhone.text = String.format(phone, mobile)
    }

    override fun onDestroy()
    {
        Tool.cancelCountDown()
        super.onDestroy()
    }

    override fun loginSuccess(data: LoginVo)
    {
        RxToast.success("登录成功")
        EventBus.getDefault()
                .post(Constant.EVENT_PAY_FAILED)
        data.birthStringDay = Util.getTimeStr(data.birthDay)
        SpTool.saveString(Constant.STR_TOKEN, data.appToken)
        SpTool.saveLong(Constant.LONG_TOKEN, Date().time)
        SpTool.saveString(Constant.STR_MOBILE, data.mobile)
        SpTool.saveString(Constant.STR_USER_PHOTO, data.headImg)
        SpTool.saveString(Constant.STR_USER_NAME, data.userName)
        SpTool.saveObject(Constant.OBJ_LOGIN, data)
        if (RegTool.isEmpty(data.mobile))
        {
            showDialog(SweetAlertDialog.NORMAL_TYPE, "是否立即绑定手机？", "", "是", "否", {
                start(BindMobileActivity::class.java)
                disDialog()
                finish()
            }, {
                           disDialog()
                           finish()
                       })
        }
        else
        {
            finish()
        }
    }

    override fun onResume()
    {
        super.onResume()
        if (wxLogin)
        {
            wxLogin()
        }
    }

    private fun wxLogin()
    {
        wxLogin = false
        val body = BaseModel()
        body.code = code
        mPresenter.getData(HttpDto(Constant.WX_Login, body))
    }

    // --------------- EventBus ---------------
    var code = ""
    var wxLogin = false
    @Subscribe
    fun onEvent(event: WXEvent)
    {
        code = event.code
        wxLogin = true
    }
}